/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.*;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;
import logica.GeneradorDocumentos;
import logica.MailSender;

/**
 *
 * @author Smuggler
 */
public class EditarAlquileres extends JPanel {

    public static JFrame frame;
    entities.Alquileres a;
    private List listactualizaTabla;
    private List listaTemp;
    String tipoAlquiler = "O";
    private Usuarios usuario;
    private Integer idAlquiler;
    private Alquileres alquilerGlobal;

    public EditarAlquileres(Usuarios usuario, Integer idAlquiler) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }

        this.usuario = usuario;
        this.idAlquiler = idAlquiler;
        if (idAlquiler != null) {
            actualizaTablaId(idAlquiler);
        }
        setearComboBox();
        focusFechaActual();
    }

    private void setearComboBox() {
        Query queryUnidades = entityManager.createNamedQuery("UnidadesAlojamiento.findAll");
        List<UnidadesAlojamiento> unidadesList = queryUnidades.getResultList();
        for (UnidadesAlojamiento unidadesAlojamiento : unidadesList) {
            unidadAlojamientoComboBox.addItem(unidadesAlojamiento);
        }
        UnidadesAlojamiento ua = new UnidadesAlojamiento();
        ua.setNombre("TODOS");
        unidadAlojamientoComboBox.addItem(ua);
        unidadAlojamientoComboBox.setSelectedItem(ua);
    }

    public JFrame getFrame() {
        return frame;
    }

    public void setFrame(JFrame frame) {
        EditarAlquileres.frame = frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Alquileres a WHERE a.tipoAlquiler = 'O' ORDER BY a.fechaArribo DESC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        unidadesAlojamientoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery.getResultList();
        unidadesAlojamientoQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery1.getResultList();
        clientesQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c  ORDER BY c.apellido");
        clientesList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery.getResultList();
        clientesQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery1.getResultList();
        buttonGroup1 = new javax.swing.ButtonGroup();
        clientesQuery2 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery2.getResultList();
        unidadesAlojamientoQuery2 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery2.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        cancelarButton = new javax.swing.JButton();
        ayudaLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        apellidoLabel = new javax.swing.JLabel();
        apellidoField = new javax.swing.JTextField();
        buscarButton = new javax.swing.JButton();
        unidadAlojamientoComboBox = new javax.swing.JComboBox();
        unidadAlojamientoLabel = new javax.swing.JLabel();
        fechaArriboDateChooser = new com.toedter.calendar.JDateChooser();
        fechaPartidaDateChooser = new com.toedter.calendar.JDateChooser();
        jLabel4 = new javax.swing.JLabel();
        fechaArriboLabel = new javax.swing.JLabel();
        resetButton = new javax.swing.JButton();
        exportarExcelButton = new javax.swing.JButton();
        checkInButton = new javax.swing.JButton();
        contratoButton = new javax.swing.JButton();
        sendEmail = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        masterTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idAlquiler}"));
        columnBinding.setColumnName("Codigo Alquiler");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idUnidadAlojamiento}"));
        columnBinding.setColumnName("Unidad Alojamiento");
        columnBinding.setColumnClass(entities.UnidadesAlojamiento.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idCliente}"));
        columnBinding.setColumnName("Cliente");
        columnBinding.setColumnClass(entities.Clientes.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaArribo}"));
        columnBinding.setColumnName("Fecha Arribo");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaPartida}"));
        columnBinding.setColumnName("Fecha Partida");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${montoTotal}"));
        columnBinding.setColumnName("Monto Total");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${montoReserva}"));
        columnBinding.setColumnName("Monto Reserva");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cantidadPersonas}"));
        columnBinding.setColumnName("Cantidad Personas");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoAlquiler}"));
        columnBinding.setColumnName("Estado Alquiler");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(8).setMinWidth(0);
        masterTable.getColumnModel().getColumn(8).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(8).setMaxWidth(0);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar Alquiler/es");
        cancelarButton.setActionCommand("Cancelar Alquiler");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        apellidoLabel.setText("Apellido:");

        buscarButton.setBackground(new java.awt.Color(1, 154, 210));
        buscarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        buscarButton.setForeground(new java.awt.Color(255, 255, 255));
        buscarButton.setText("Buscar");
        buscarButton.addActionListener(formListener);

        unidadAlojamientoLabel.setText("Unidad de Alojamiento:");

        jLabel4.setText("Fecha Partida:");

        fechaArriboLabel.setText("Fecha Arribo:");

        resetButton.setBackground(new java.awt.Color(1, 154, 210));
        resetButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        resetButton.setForeground(new java.awt.Color(255, 255, 255));
        resetButton.setText("Resetear Busqueda");
        resetButton.addActionListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        checkInButton.setBackground(new java.awt.Color(255, 153, 0));
        checkInButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        checkInButton.setForeground(new java.awt.Color(255, 255, 255));
        checkInButton.setText("Generar Check-In Card");
        checkInButton.setEnabled(false);
        checkInButton.addActionListener(formListener);

        contratoButton.setBackground(new java.awt.Color(255, 153, 0));
        contratoButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        contratoButton.setForeground(new java.awt.Color(255, 255, 255));
        contratoButton.setText("Generar Contrato de Alquiler");
        contratoButton.setEnabled(false);
        contratoButton.addActionListener(formListener);

        sendEmail.setBackground(new java.awt.Color(255, 153, 0));
        sendEmail.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        sendEmail.setForeground(new java.awt.Color(255, 255, 255));
        sendEmail.setText("Enviar Datos de Reserva por mail");
        sendEmail.setEnabled(false);
        sendEmail.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(exportarExcelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(resetButton)
                        .addGap(18, 18, 18)
                        .addComponent(buscarButton)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(apellidoLabel)
                            .addComponent(unidadAlojamientoLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(apellidoField)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(unidadAlojamientoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(fechaArriboLabel)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(fechaArriboDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(fechaPartidaDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(355, 355, 355))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(checkInButton, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(contratoButton)
                        .addGap(18, 18, 18)
                        .addComponent(sendEmail)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancelarButton)
                        .addContainerGap())))
            .addComponent(jSeparator1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(contratoButton)
                    .addComponent(checkInButton)
                    .addComponent(cancelarButton)
                    .addComponent(sendEmail))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fechaArriboLabel)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(6, 6, 6)
                                        .addComponent(apellidoLabel))
                                    .addComponent(apellidoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(fechaArriboDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fechaPartidaDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(3, 3, 3)
                                        .addComponent(unidadAlojamientoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(9, 9, 9)
                                        .addComponent(unidadAlojamientoLabel))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(9, 9, 9)
                                        .addComponent(jLabel4)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(exportarExcelButton)
                                .addGap(4, 4, 4))
                            .addComponent(ayudaLabel)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(buscarButton)
                            .addComponent(resetButton))
                        .addContainerGap())))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == cancelarButton) {
                EditarAlquileres.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == buscarButton) {
                EditarAlquileres.this.buscarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == resetButton) {
                EditarAlquileres.this.resetButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                EditarAlquileres.this.exportarExcelButtonActionPerformed(evt);
            }
            else if (evt.getSource() == checkInButton) {
                EditarAlquileres.this.checkInButtonActionPerformed(evt);
            }
            else if (evt.getSource() == contratoButton) {
                EditarAlquileres.this.contratoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == sendEmail) {
                EditarAlquileres.this.sendEmailActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                EditarAlquileres.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                EditarAlquileres.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                EditarAlquileres.this.masterTableMousePressed(evt);
            }
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();

    }

    public void focusFechaActual() {

        //Guardo la fecha actual 
        Date fechaActualtest = new Date();
        //Recorro para buscar la fecha mas cercana a la fecha actual       
        int filaFechaCercana = 0;
        for (Alquileres alquileres : list) {
            //Si la fecha es mayor, voy guardando los numero de las filas
            if (alquileres.getFechaArribo().compareTo(fechaActualtest) > 0) {

                filaFechaCercana++;
            }
            //Si la fecha es menor o igual a la actual, me muevo a la ultima fecha mayor cercana a  la actual
            if (alquileres.getFechaArribo().compareTo(fechaActualtest) <= 0) {
                masterTable.scrollRectToVisible(masterTable.getCellRect(filaFechaCercana, 0, true));

            }

        }

    }

    private void actualizaTablaId(Integer idAlquiler) {

        Query query;


        query = entityManager.createNamedQuery("Alquileres.findByIdAlquiler").setParameter("idAlquiler", idAlquiler);

        listactualizaTabla = query.getResultList();

        list.clear();
        list.addAll(listactualizaTabla);



    }

    private String formatearFecha(Date fecha) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fecha);
        String salida = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR) + " a las " + cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE);
        return salida;
    }

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar la cancelacion del alquiler/es seleccionados?", "Cancelación de Alquileres", JOptionPane.YES_NO_OPTION);
        Logs logs;
        if (respuesta == JOptionPane.YES_OPTION) {
            try {
                int[] selected = masterTable.getSelectedRows();
                for (int idx = 0; idx < selected.length; idx++) {
                    entities.Alquileres c = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                    c.setTipoAlquiler("B");
                    logs = new Logs();
                    logs.setUsuario(usuario);
                    logs.setearObservaciones("Baja", "Alquileres", c.getIdAlquiler(), "EditarAlquileres");
                    entityManager.persist(logs);
                }
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.Alquileres> merged = new ArrayList<entities.Alquileres>(list.size());
                for (entities.Alquileres a : list) {
                    merged.add(entityManager.merge(a));
                }

                list.clear();
                list.addAll(merged);
            }
            habilitarBotones(false);
            refrescar();
        }
    }//GEN-LAST:event_cancelarButtonActionPerformed
    private void habilitarBotones(boolean estado) {
        cancelarButton.setEnabled(estado);
        //   masterTable.setEnabled(!estado);
        checkInButton.setEnabled(estado);
        contratoButton.setEnabled(estado);
        sendEmail.setEnabled(estado);
    }

    private void limpiarBotones() {
        apellidoField.setText("");
        unidadAlojamientoComboBox.setSelectedIndex(0);
        fechaArriboDateChooser.setDate(null);
        fechaPartidaDateChooser.setDate(null);

    }
    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        buscarAlquilerXid();
    }//GEN-LAST:event_masterTableMouseClicked

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("Seleccione los alquileres que desea eliminar y luego presione borrar, esta opcion afectara la base de datos del sistema");
    }//GEN-LAST:event_ayudaLabelMouseEntered
    private void actualizaTabla() {
        String apellido;
        Query query;
        apellido = apellidoField.getText();
        Date fechaPartida = fechaPartidaDateChooser.getDate();
        Date fechaArribo = fechaArriboDateChooser.getDate();
        UnidadesAlojamiento unidadAlojamiento = (UnidadesAlojamiento) unidadAlojamientoComboBox.getSelectedItem();
        Calendar fechaPartidaFinal, fechaArriboInicial;

        if (unidadAlojamiento.getNombre().equals("TODOS")) {
            unidadAlojamiento = null;
        }
        if (fechaPartidaDateChooser.getDate() == null) {
            fechaPartidaFinal = Calendar.getInstance();
            fechaPartidaFinal.set(Calendar.YEAR, 9999);
            fechaPartida = fechaPartidaFinal.getTime();
        }
        if (fechaArriboDateChooser.getDate() == null) {
            fechaArriboInicial = Calendar.getInstance();
            fechaArriboInicial.set(Calendar.YEAR, 1900);
            fechaArribo = fechaArriboInicial.getTime();
        }
        query = entityManager.createNamedQuery("Alquileres.findByTodo").setParameter("apellidoCliente", apellido).setParameter("UnidadAlojamiento", unidadAlojamiento).setParameter("fechaFin", fechaPartida).setParameter("fechaInicio", fechaArribo).setParameter("tipoalquiler", "O").setParameter("tipoalquiler2", "");

        listactualizaTabla = query.getResultList();

        list.clear();
        list.addAll(listactualizaTabla);
        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No se encontro ningun resultado, revise los campos de busqueda", "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        }


    }
    private void buscarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarButtonActionPerformed

        actualizaTabla();       // TODO add your handling code here:
    }//GEN-LAST:event_buscarButtonActionPerformed

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        refrescar();

    }//GEN-LAST:event_resetButtonActionPerformed

    private void masterTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMousePressed
        habilitarBotones(true);       // TODO add your handling code here:
        buscarAlquilerXid();

    }//GEN-LAST:event_masterTableMousePressed

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Alquileres").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    private void buscarAlquilerXid() {
        Query queryLocal;
        int idAlquilerLocal = Integer.parseInt(String.valueOf(masterTable.getValueAt(masterTable.getSelectedRow(), 0)));
        queryLocal = entityManager.createNamedQuery("Alquileres.findByIdAlquiler").setParameter("idAlquiler", idAlquilerLocal);
        listaTemp = queryLocal.getResultList();
        alquilerGlobal = (Alquileres) listaTemp.get(0);

    }
    private void checkInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkInButtonActionPerformed
        // Aca le paso los datos a Generador de Documentos para que cree el documento de checkin
        ////-----------//////    buscarAlquilerXid();
        Calendar cal = Calendar.getInstance();
        Calendar calArribo = Calendar.getInstance();

        Date fechaPartida = ((Date) (alquilerGlobal.getFechaPartida()));
        cal.setTime(fechaPartida);
        String fechaPartidaStr = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + (cal.get(Calendar.YEAR));


        Date fechaArribo = ((Date) (alquilerGlobal.getFechaArribo()));
        calArribo.setTime(fechaArribo);


        String diaArribo = String.valueOf(calArribo.get(Calendar.DATE));
        String mesArribo = String.valueOf((calArribo.get(Calendar.MONTH) + 1));
        String anioArribo = String.valueOf(calArribo.get(Calendar.YEAR));
        String clienteContrato = alquilerGlobal.getIdCliente().getApellido() + ", " + alquilerGlobal.getIdCliente().getNombres();
        String unidad = alquilerGlobal.getIdUnidadAlojamiento().getNombre();
        String personas = String.valueOf(alquilerGlobal.getCantidadPersonas());
        String total = String.valueOf(alquilerGlobal.getMontoTotal());
        String codigo = String.valueOf(alquilerGlobal.getIdAlquiler());
        String documento = alquilerGlobal.getIdCliente().getDocumento();

        GeneradorDocumentos generadorDocumentos = new GeneradorDocumentos();
        generadorDocumentos.imprimirTarjetaCheckIn(codigo, documento, diaArribo, mesArribo, anioArribo, personas, clienteContrato, unidad, fechaPartidaStr, total);
    }//GEN-LAST:event_checkInButtonActionPerformed

    private void contratoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contratoButtonActionPerformed
        // Acale paso los datos a Generador de Documentos para que cree el documento de contrato de alquiler
        Calendar cal = Calendar.getInstance();
        Calendar calArribo = Calendar.getInstance();

        Date fechaPartida = ((Date) (alquilerGlobal.getFechaPartida()));
        cal.setTime(fechaPartida);
        String fechaPartidaStr = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + (cal.get(Calendar.YEAR));


        Date fechaArribo = ((Date) (alquilerGlobal.getFechaArribo()));
        calArribo.setTime(fechaArribo);


        String diaArribo = String.valueOf(calArribo.get(Calendar.DATE));
        String mesArribo = String.valueOf((calArribo.get(Calendar.MONTH) + 1));
        String anioArribo = String.valueOf(calArribo.get(Calendar.YEAR));
        String clienteContrato = alquilerGlobal.getIdCliente().getApellido() + ", " + alquilerGlobal.getIdCliente().getNombres();
        String unidad = alquilerGlobal.getIdUnidadAlojamiento().getNombre();
        String personas = String.valueOf(alquilerGlobal.getCantidadPersonas());
        String total = String.valueOf(alquilerGlobal.getMontoTotal());
        String codigo = String.valueOf(alquilerGlobal.getIdAlquiler());
        String documento = alquilerGlobal.getIdCliente().getDocumento();

        GeneradorDocumentos generadorDocumentos = new GeneradorDocumentos();
        generadorDocumentos.imprimirContrato(codigo, documento, diaArribo, mesArribo, anioArribo, personas, clienteContrato, unidad, fechaPartidaStr, total);

    }//GEN-LAST:event_contratoButtonActionPerformed

    private void sendEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendEmailActionPerformed


        if (!"".equals(alquilerGlobal.getIdCliente().getEmail())) {
            {
                int i = JOptionPane.showConfirmDialog(this, "Desea enviar mail de confirmación de reserva al cliente?", "Enviar e-mail", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (i == 0) {

                    //Busqueda de datos de configuración
                    ConfiguracionMail configMail = entityManager.find(ConfiguracionMail.class, 1);

                    //Envio mail de confirmación

                    Date llegadaCalendar = alquilerGlobal.getFechaArribo();
                    Date partidaCalendar = alquilerGlobal.getFechaPartida();
                    String codigo = ((Integer) (masterTable.getValueAt(masterTable.getSelectedRow(), 0))).toString();
                    String llegada = String.valueOf(llegadaCalendar.getDate()) + "/" + String.valueOf(llegadaCalendar.getMonth() + 1) + "/" + String.valueOf(llegadaCalendar.getYear() + 1900);
                    String partida = String.valueOf(partidaCalendar.getDate()) + "/" + String.valueOf(partidaCalendar.getMonth() + 1) + "/" + String.valueOf(partidaCalendar.getYear() + 1900);

                    String smtpHost = configMail.getSmtpHostmail();
                    Integer port = configMail.getPortMail();
                    String fromMail = configMail.getFromMail();
                    String user = configMail.getUserMail();
                    String pass = configMail.getPassMail();

                    String toMail = alquilerGlobal.getIdCliente().getEmail().toString();
                    String textMail = "CONFIRMACION DE RESERVA\n\nNombre y Apellido: " + alquilerGlobal.getIdCliente().getNombres() + " " + alquilerGlobal.getIdCliente().getApellido()
                            + "\nCodigo de Reserva: " + codigo
                            + "\nCheck-in: " + llegada
                            + "\nCheck-out: " + partida
                            + "\nCantidad de Personas: " + alquilerGlobal.getCantidadPersonas()
                            + "\nSe aloja en: " + alquilerGlobal.getIdUnidadAlojamiento().getNombre()
                            + "\nTotal del Alquiler: $" + alquilerGlobal.getMontoTotal();

                    MailSender mailSender = new MailSender();
                    mailSender.sendEmail(smtpHost, port, fromMail, user, pass, toMail, textMail);
                }

            }
        } else {
            JOptionPane.showMessageDialog(this, "No se encontro ningun Email asociado al Cliente", "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        }

    }//GEN-LAST:event_sendEmailActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField apellidoField;
    private javax.swing.JLabel apellidoLabel;
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton buscarButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton checkInButton;
    private java.util.List<entities.Clientes> clientesList;
    private java.util.List<entities.Clientes> clientesList1;
    private java.util.List<entities.Clientes> clientesList2;
    private javax.persistence.Query clientesQuery;
    private javax.persistence.Query clientesQuery1;
    private javax.persistence.Query clientesQuery2;
    private javax.swing.JButton contratoButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private com.toedter.calendar.JDateChooser fechaArriboDateChooser;
    private javax.swing.JLabel fechaArriboLabel;
    private com.toedter.calendar.JDateChooser fechaPartidaDateChooser;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private java.util.List<entities.Alquileres> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.persistence.Query query;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton sendEmail;
    private javax.swing.JComboBox unidadAlojamientoComboBox;
    private javax.swing.JLabel unidadAlojamientoLabel;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList1;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList2;
    private javax.persistence.Query unidadesAlojamientoQuery;
    private javax.persistence.Query unidadesAlojamientoQuery1;
    private javax.persistence.Query unidadesAlojamientoQuery2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user, Integer idAlqui) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditarAlquileres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditarAlquileres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditarAlquileres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditarAlquileres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        final Usuarios usuario = user;
        final Integer idAlquiler = idAlqui;
        EditarAlquileres.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new EditarAlquileres(usuario, idAlquiler));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Administración   -   Alquileres   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame.isVisible()) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
